# -*- coding: utf-8 -*-

import os
import sys
from contextlib import closing
import math
import jinja2
import hashlib
import time
import werkzeug.utils
import datetime
import openerp
import simplejson
from openerp import http
from openerp.http import request
from openerp.modules.registry import RegistryManager
from reportlab.graphics.barcode import createBarcodeDrawing
from openerp.addons.wechat.enterprise import WxApi, WxApplication, WxTextResponse, WxNewsResponse, WxArticle, WxLink
from openerp.addons.website_mshop.pools import ModelPool, CursorProxy, common_functions, PageProxy, _slug
from openerp.addons.dftg_weixin.application.application_work import WxAppCorpWork
import pytz
ISODATEFORMAT = '%Y-%m-%d'
ISODATETIMEFORMAT = "%Y-%m-%d %H:%M:%S"
SUPERUSER_ID = 1

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment(block_start_string='<%', block_end_string='%>'
                         , variable_start_string='${', variable_end_string='}'
                         , loader=loader, autoescape=True)


class WeixinAppWorkController(http.Controller):
    weixin_app = None

    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals['_slug'] = _slug
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps
        self.weixin_app = WxAppCorpWork()

    # 微信回调入口网址
    @http.route('/weixin/app/work', auth='public')
    def weixin(self, **kw):
        result = self.weixin_app.process(request.httprequest.args, request.httprequest.data)
        return result


    # auth test
    @http.route('/weixin/test', auth='weixin')
    def test_weixin_auth(self, **kw):
        oauth_uid = request.session.oauth_uid
        return 'hello, %s' % (oauth_uid,)
